#!/bin/sh
#
# 当使用JetBrains公司的CLion+Activity Tracker插件时，在涉及main.c的变更情况下，添加键盘与鼠标记录文件
#

if test ! -f .commit
then
    exit
fi

rm .commit

function get_jetbrains_appdata_path {
    if grep -i microsoft /proc/version > /dev/null 2>&1
    then
        jetbrains_appdata_path=$(cmd.exe /c "echo %appdata%\JetBrains" |iconv -f gbk -t utf-8 |sed -e 's/\\/\//g' -e "s/\(.*\):/\/mnt\/\L\1/" | tr -d '\r')
    elif grep -i mingw /proc/version > /dev/null 2>&1
    then
        jetbrains_appdata_path=$(cmd.exe //c "echo %appdata%\JetBrains" |iconv -f gbk -t utf-8 |sed -e 's/\\/\//g' -e "s/\(.*\):/\/\L\1/" | tr -d '\r')
    fi

    echo "$jetbrains_appdata_path"
}

maybe_main_c_filepath=$(git show HEAD --name-only --oneline |tail -n '+2' |grep main.c)
if [ "$maybe_main_c_filepath" != "" ]; then
    main_c_filepath="$maybe_main_c_filepath"
    echo "main.c filepath" $main_c_filepath
    main_c_dirname=$(dirname $main_c_filepath)
        
    jetbrains_appdata_path=$(get_jetbrains_appdata_path)
    
    maybe_track_filepath=$(find $jetbrains_appdata_path -path "*/CLion*" -name "ide-events.csv" -printf "%T@ %p\n" | sort -n -r |head -1 | cut -d' ' -f 2 |tr -d [\\r])
	
    if test "$maybe_track_filepath" != ""
    then
        rm -f .commit
        echo "HIHI"
        echo "copying ${maybe_track_filepath} to $main_c_dirname/$(basename ${maybe_track_filepath})"

        cp $maybe_track_filepath $main_c_dirname
        git add $main_c_dirname/$(basename $maybe_track_filepath)
        git commit -n --amend -C HEAD
    else
	    cat <<\EOF
在Jetbrains CLion程序目录$jetbrains_appdata_path里没找到Activity Tracker的ide-events.csv文件
请确保在CLion里安装了Activity Tracker软件并启用了记录键盘和鼠标事件。
EOF
	    exit 1
    fi
fi

exit

